'use strict';
const mongoose = require('mongoose');
const config = require('../config/config.unittest.js')({});
const fs = require('fs');
const readline = require('readline');
const moment = require('moment');
const _ = require('lodash');

let ParserBetter = require('../app/utils/rss/parser');
let parserBetter = new ParserBetter({timeout: 10000});

const UserModel = require('../app/model/User')({
  mongoose,
});
const TopicModel = require('../app/model/Topic')({
  mongoose,
});
const TopicCollectModel = require('../app/model/TopicCollect')({
  mongoose,
});
const MessageModel = require('../app/model/Message')({
  mongoose,
});


mongoose.connect(config.mongoose.url, config.mongoose.options, function (err) {
  if (err) {
    console.error('connect to %s error: ', config.mongoose, err.message);
    process.exit(1);
  }
});

main();

async function main() {
  await crud();
  process.exit(0);
}


async function crud() {
  // let ttt = await TopicModel.count({tab: 'tech', tags: {$exists: true}})
  // console.log(ttt);

  // let topics = await TopicModel.find({author_name: '51CTO', tab: 'tech', tags: {$exists: true}})
  let topics = await TopicModel.find({author_name: '掘金', tab: 'tech'})
  // .skip(0).limit(3000);

  for (let i = 0; i < topics.length; i++) {
    let topic = topics[i];
    cleanTags(topic.tags);
    await TopicModel.findByIdAndUpdate({_id: topic.id}, {$set: {tags: topic.tags}});
    console.log(i, topics.length);
  }

}


function cleanTags(tags) {
  for (let i = 0; i < tags.length; i++) {
    let tag = tags[i];
    tags[i] = tag.split(' ').map(v => _.upperFirst(v)).join(' ')
      .split('-').map(v => _.upperFirst(v)).join('-');
  }
}
